package com.erp.serviceIMP;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.danga.MemCached.MemCachedClient;
import com.erp.dao.DataSourceDAO;
import com.erp.entity.DataSource;
import com.erp.exception.MyException;
import com.erp.service.DataSourceService;
@Service("dataSourceService")
public class DataSourceServiceIMP implements DataSourceService {
    
    @Autowired
    private MemCachedClient memcachedClient;
    @Autowired
    private DataSourceDAO dataSourceMapper;

    private static final int maxRecord=9999;
    
    public MemCachedClient getMemcachedClient() {
        return memcachedClient;
    }

    public void setMemcachedClient(MemCachedClient memcachedClient) {
        this.memcachedClient = memcachedClient;
    }

    public DataSourceDAO getDataSourceMapper() {
        return dataSourceMapper;
    }

    public void setDataSourceMapper(DataSourceDAO dataSourceMapper) {
        this.dataSourceMapper = dataSourceMapper;
    }

    public List<DataSource> findAll() {
        List<DataSource> list = new ArrayList<DataSource>();
        try {
            DataSource dataSource = null;
            for (int i = 0; i < maxRecord; i++) {
                dataSource = (DataSource) memcachedClient.get(keyStrategy(i));
                if (dataSource != null) {
                    list.add(dataSource);
                }
            }
            if (list.size() == 0) {
                list = dataSourceMapper.findAll();
                for (DataSource ds : list) {
                    memcachedClient.add(keyStrategy(ds.getId()), ds);
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return list;
    }

    public DataSource findById(int id) {
        DataSource ds = (DataSource) memcachedClient.get(keyStrategy(id));
        if(ds==null){
            ds = dataSourceMapper.findById(id);
            if(ds!=null){
                memcachedClient.add(keyStrategy(id), ds);
            }
        }
        return ds;
    }

    public void update(DataSource dataSource) throws Exception {
        dataSourceMapper.update(dataSource);
        memcachedClient.set(keyStrategy(dataSource.getId()), dataSource);
    }

    public int insert(DataSource dataSource) throws Exception {
        dataSourceMapper.insert(dataSource);
        int id=dataSource.getId();
        memcachedClient.set(keyStrategy(id), dataSource);
        return id;
    }

    public void delete(int id) throws Exception {
       dataSourceMapper.delete(id);
       memcachedClient.delete(keyStrategy(id));
    }
    
    private String keyStrategy(int id){
        return "datasource" + id;
    }

}
